package com.dts.evaluate.ui.activity;

import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Html;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.ScaleAnimation;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.dts.evaluate.APP;
import com.dts.evaluate.R;
import com.dts.evaluate.bean.EvaluateBean;
import com.dts.evaluate.bean.SocketBean;
import com.dts.evaluate.common.Constants;
import com.dts.evaluate.common.SocketType;
import com.dts.evaluate.ui.view.TitleView;
import com.dts.evaluate.utils.DensityUtil;
import com.dts.evaluate.utils.LogUtil;
import com.dts.evaluate.utils.SocketUtil;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;


public class EvaluateActivity extends BaseActivity implements View.OnClickListener, TitleView.OnBackClikListener {


    @Bind(R.id.title_view)
    TitleView titleView;
    @Bind(R.id.layout1)
    RelativeLayout layout1;
    @Bind(R.id.layout2)
    RelativeLayout layout2;
    @Bind(R.id.layout3)
    RelativeLayout layout3;
    @Bind(R.id.layout4)
    RelativeLayout layout4;
    @Bind(R.id.layout5)
    RelativeLayout layout5;
    @Bind(R.id.layout6)
    RelativeLayout layout6;
    @Bind(R.id.evaluate_layout)
    LinearLayout evaluateLayout;
    private MediaPlayer mediaPlayer;
    private AssetFileDescriptor afd1;
    private AssetFileDescriptor afd2;

    private EvaluateBean evaluateBean;
    private Timer timer;
    private ScaleAnimation scaleAnimation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_evaluate);
        ButterKnife.bind(this);

        Intent intent = getIntent();
        evaluateBean = (EvaluateBean) intent.getSerializableExtra(Constants.EVALUATE_BEAN);

        //初始化缩放动画
        scaleAnimation = new ScaleAnimation(1.5f, 0.5f, 1.5f, 0.5f, 50, 50);
        scaleAnimation.setDuration(100);
        scaleAnimation.setRepeatMode(Animation.REVERSE);
        scaleAnimation.setRepeatCount(100);
        scaleAnimation.setInterpolator(new LinearInterpolator());


        //初始化音乐文件 和mediaPlayer
        afd1 = getResources().openRawResourceFd(R.raw.praise_notic);
        afd2 = getResources().openRawResourceFd(R.raw.praise_thank);
        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(afd1.getFileDescriptor(), afd1.getStartOffset(), afd1.getLength());
            mediaPlayer.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //初始化控件
        initView();

        //即使没有任何操作，10秒后退出评价界面
        timer = new Timer();
       timer.schedule(new TimerTask() {
            @Override
            public void run() {
                finish();
            }
        }, 15 * 1000);

    }

    /**
     * 初始化控件
     */
    private void initView() {

        layout1.setOnClickListener(this);
        layout1.setTag(1);
        layout2.setOnClickListener(this);
        layout2.setTag(2);
        layout3.setOnClickListener(this);
        layout3.setTag(3);
        layout4.setOnClickListener(this);
        layout4.setTag(4);
        layout5.setOnClickListener(this);
        layout5.setTag(5);
        layout6.setOnClickListener(this);
        layout6.setTag(6);

        titleView.setOnBackClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mediaPlayer != null) {
            mediaPlayer.start();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        APP.evaluate_flag = false;
    }

    @Override
    public void onClick(View v) {

        v.startAnimation(scaleAnimation);


        if (evaluateBean == null) {
            //showDaialog("<div style='color:#F00'>" +"评价失败"+ "</div>");
            showErrorDialog("评价结果","评价失败");
            return;
        }
        evaluateBean.setResult((Integer) v.getTag());
        final Gson gson = new Gson();
        String msg = gson.toJson(evaluateBean);
        SocketUtil.communicate(msg, SocketType.TYPE_EVALUATE, SocketType.CALL_BACK_EVALUATE_RESULT, new SocketUtil.SocketCallback() {
            @Override
            public void onSuccess(String payload) {
                SocketBean<JsonObject> socketBean = gson.fromJson(payload, new TypeToken<SocketBean<JsonObject>>() {
                }.getType());
                JsonObject msg = socketBean.getMsg();
                LogUtil.v("msg:"+msg);
                EvaluateBean evaluateBean = gson.fromJson(msg, EvaluateBean.class);
                int state = evaluateBean.getState();
                String message = evaluateBean.getMessage();
                if (state == 1) {
                    showSuccessDialog("评价结果",message);
                    try {
                        if (timer != null) {
                            timer.cancel();
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    Timer timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            finish();
                        }
                    }, 500);
                } else {
                    showErrorDialog("评价结果",message);
                }




            }

            @Override
            public void onError(String error) {
                showDaialog("<div style='color:#F00'>" + error + "</div>");
            }
        });

        playThinkRaw();

    }

    /**
     * 显示评价结果对话框
     *
     * @param msg
     */
    private void showDaialog(String msg) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("评价结果");
        TextView textView = new TextView(this);
        textView.setGravity(Gravity.CENTER);
        textView.setTextSize(DensityUtil.sp2px(this, 20));
        textView.setPadding(20, 0, 0, 0);
        textView.setText(Html.fromHtml(msg));
        builder.setView(textView);
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    /**
     * 播放谢谢 MP3
     */
    private void playThinkRaw() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            mediaPlayer.stop();
        }
        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource(afd2.getFileDescriptor(), afd2.getStartOffset(), afd2.getLength());
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                }
            });
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onTitleViewClik(View v) {
        finish();
    }
}
